import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'dart:async';
import '../utils/request.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:audio_video_progress_bar/audio_video_progress_bar.dart';
import 'package:wakelock/wakelock.dart';

class VideoSwiper2 extends StatefulWidget {
  var arguments;
  VideoSwiper2({Key? key, this.arguments}) : super(key: key);

  @override
  _VideoSwiper2State createState() => _VideoSwiper2State(this.arguments);
}

class _VideoSwiper2State extends State<VideoSwiper2> {
  var arguments;
  _VideoSwiper2State(this.arguments);
  late VideoPlayerController _controllerActive;
  int _pageIndex = 0;
  List _videoIds = <int>[];
  late PageController _pageController;
  int _oldIndex = 0; // 上一次的索引
  double _radio = 16 / 9;
  int _playingIndex = 0;
  bool _autoNextRuning = false;
  int _durationActive = 0;
  int _positionActive = 0;
  int _buffered = 0;
  @override
  void initState() {
    super.initState();
    _controllerActive = VideoPlayerController.network('');
    this.setState(() {
      _oldIndex = arguments['currentIndex'];
      _pageIndex = arguments['currentIndex'];
      _videoIds = arguments['ids'];
    });
    _getVideoUrl(_videoIds[_pageIndex]);
    _pageController = PageController(
      initialPage: _pageIndex,
    );
    Wakelock.enable();
  }

  void _initVideoActive(String _src) {
    _controllerActive = VideoPlayerController.network(_src)
      ..initialize().then((_) {
        // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
        _controllerActive.play();
        var _duration = _controllerActive.value.duration.inMilliseconds;
        this.setState(() {
          _durationActive = _controllerActive.value.duration.inSeconds;
        });
        _controllerActive.addListener(() {
          var _position = _controllerActive.value.position.inMilliseconds;
          if (_duration == _position) {
            //代表播放完了，要自动跳转到下一个视频
            if (_autoNextRuning) return; // 避免多次执行
            _autoNextPage();
            setState(() {
              _oldIndex = _pageIndex;
              _autoNextRuning = true;
            });
          } else if (4500 < _duration - _position &&
              _duration - _position < 5000) {
            // 还剩5秒钟时候提示
            EasyLoading.showToast("5秒钟后将自动切换下一个");
          }
          this.setState(() {
            _positionActive = _controllerActive.value.position.inSeconds;
            _buffered = _controllerActive.value.buffered.length != 0
                ? _controllerActive.value.buffered[0].end.inSeconds
                : 0;
          });
        });
        setState(() {
          _radio = _controllerActive.value.aspectRatio;
          _playingIndex = _pageIndex;
          _autoNextRuning = false;
        });
        EasyLoading.dismiss();
      });
  }

  void _autoNextPage() {
    Timer(Duration(milliseconds: 200), () {
      // 模拟手动滑屏操作
      setState(() {
        _oldIndex = _pageIndex;
      });
      _getVideoUrl(_videoIds[_pageIndex]);
    });
    _pageController.nextPage(
      duration: Duration(milliseconds: 200),
      curve: Curves.linear,
    );
  }

  void _getVideoUrl(int id) async {
    EasyLoading.show(status: 'loading...');
    var res = await getHttp('/mv/url?id=$id&r=960');
    var _url = res['data']['url'];
    var _newUrl = _url.replaceAll('http', 'https');
    _initVideoActive(_newUrl);
  }

  @override
  void dispose() {
    super.dispose();
    _controllerActive.dispose();
    Wakelock.disable();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(
      //   title: Text("videoswiper2"),
      // ),
      body: Listener(
        onPointerDown: (_index) {
          setState(() {
            _oldIndex = _pageIndex;
          });
        },
        onPointerUp: (_index) {
          Timer(Duration(milliseconds: 200), () {
            if (_oldIndex != _pageIndex) {
              // 一次有效的滑动切换
              setState(() {
                _oldIndex = _pageIndex;
              });
              _getVideoUrl(_videoIds[_pageIndex]);
            }
          });
        },
        child: PageView.builder(
          onPageChanged: (p) {
            _controllerActive.pause();
            setState(() {
              _pageIndex = p;
            });
          },
          controller: _pageController,
          scrollDirection: Axis.vertical,
          itemCount: _videoIds.length,
          itemBuilder: (context, index) {
            return _playingIndex == index
                ? Container(
                    color: Colors.black87,
                    child: Stack(
                      children: [
                        Align(
                          alignment: Alignment.center,
                          child: Container(
                            child: AspectRatio(
                              aspectRatio: _radio,
                              child: VideoPlayer(_controllerActive),
                            ),
                          ),
                        ),
                        Align(
                          alignment: Alignment(1, 0.8),
                          child: Container(
                            width: 100.w,
                            height: 460.w,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Icon(
                                  Icons.thumb_up,
                                  size: 60.w,
                                  color: Colors.white,
                                ),
                                Icon(
                                  Icons.assignment,
                                  size: 60.w,
                                  color: Colors.white,
                                ),
                                Icon(
                                  Icons.share,
                                  size: 60.w,
                                  color: Colors.white,
                                ),
                                Icon(
                                  Icons.today_outlined,
                                  size: 60.w,
                                  color: Colors.white,
                                ),
                              ],
                            ),
                          ),
                        ),
                        Align(
                          alignment: Alignment(0, 0.98),
                          child: Container(
                            padding: EdgeInsets.symmetric(horizontal: 60.w),
                            child: ProgressBar(
                              progress: Duration(seconds: _positionActive),
                              buffered: Duration(seconds: _buffered),
                              total: Duration(seconds: _durationActive),
                              progressBarColor: Colors.grey.withOpacity(0.4),
                              baseBarColor: Colors.grey.withOpacity(0.1),
                              bufferedBarColor: Colors.grey.withOpacity(0.24),
                              thumbColor: Colors.grey[800],
                              barHeight: 12.w,
                              thumbRadius: 16.w,
                              onSeek: (duration) async {
                                await _controllerActive.seekTo(duration);
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                  )
                : Container(
                    color: Colors.black87,
                    child: Center(
                      child: Container(
                        height: 420.w,
                        color: Colors.black87,
                        child: Center(
                          child: Icon(
                            Icons.play_arrow,
                            size: 90.w,
                            color: Colors.grey,
                          ),
                        ),
                      ),
                    ),
                  );
          },
        ),
      ),
    );
  }
}
